//
//  ComposeViewController.swift
//  sinaweibowj
//
//  Created by Macintosh on 15/12/23.
//  Copyright © 2015年 mactoinsh. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    //相应方法写在最上面
    @objc private func close(){
        
        dismissViewControllerAnimated(true , completion: nil)
    }
    
    //点击图片选择器
    @objc private func selectPicture(){
        
        print(__FUNCTION__)
        //隐藏键盘
        textView.resignFirstResponder()
        
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH * 2 / 3)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            //闭包内执行刷新
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    //点击笑脸
    @objc private func selectEmoticonKeyboard(){
        print(__FUNCTION__)
    }
    
    @objc private func send(){
        
        print(__FUNCTION__)
        
        var urlString = "2/statuses/update.json"
        
        guard  let token = UserAccountViewModel().token else {
            SVProgressHUD.showInfoWithStatus("请重新登录", maskType: .Gradient)
            return
        }
        
        
        let parameters = ["access_token":token,"status":textView.text ?? ""]
        
        
        if pictureSelectorVC.imageList.count != 0 {
            //上传图片
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //调用上传图片的接口
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)
            
            NetWorkTools.sharedTools.uploadImage(urlString, parameters: parameters, imageData: imageData!, finished: { (dict, error) -> () in
                self.finishedUpdateStatus(dict , error: error )
                
            })
            
        }else {
            //发布文本微博
            NetWorkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                
                self.finishedUpdateStatus(dict, error: error)
            }
        }
    }
    
    private func finishedUpdateStatus(dict:[String:AnyObject]?,error:NSError?){
        
        if error != nil {
            SVProgressHUD.showInfoWithStatus("发送微博失败", maskType: .Gradient)
            return
        }
        
        SVProgressHUD.showInfoWithStatus("发送微博成功", maskType: .Gradient)
        self.dismissViewControllerAnimated(true , completion: nil)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        if pictureSelectorVC.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    //懒加载
    private lazy var textView:UITextView = {
        
        let tv = UITextView()
        tv.backgroundColor = UIColor.randomColor()
        //tv.text = "请输入新鲜事"
        
        tv.font = UIFont.systemFontOfSize(18)
        //打开UITextView的滚动效果
        tv.alwaysBounceVertical = true
        //滚动视图中取消键盘的第一响应者
        tv.keyboardDismissMode = .OnDrag
        
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel:UILabel = UILabel(title: "请输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    
    private lazy var pictureSelectorVC:PictureSelectorViewController = PictureSelectorViewController()
    
    
    //析构函数
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}



extension ComposeViewController:UITextViewDelegate{
    
    //要实时监测文本的改变
    func textViewDidChange(textView: UITextView) {
        
        //根据textVIew是都有文本，隐藏占位文本  开启发送按钮的交互
        placeHolderLabel.hidden = textView.hasText()
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}

extension ComposeViewController{
    
    //设置UI
    private func setupUI(){
        self.view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setToolBar()
        
        setPictureSelectorVC()
        
        //注册通知
        registerNotification()
        
    }
    
    
    @objc private func keyboardWillChange(n:NSNotification){
        print(n)
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 移动toolbar
        let offsetY = -screenH + endRect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新的方法 必须放到闭包中才有动画效果
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    //设置pictureSelectorVC
    private func setPictureSelectorVC(){
        
        //首先添加视图控制器
        addChildViewController(pictureSelectorVC)
        //添加视图控制器的跟视图
        view.addSubview(pictureSelectorVC.view)
        //工具条移到视图最顶层
        view.bringSubviewToFront(toolBar)
        //添加约束
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    
    
    //设置navigationBar
    private func setNavBar(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        //默认发送按钮不允许交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 40))
        //titleView.backgroundColor = UIColor.redColor()
        navigationItem.titleView = titleView
        
        //自定义titleView
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }
    
    //设置setTextView
    private func setTextView(){
        
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(screenH/3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    
    
    //设置setToolBar
    private func setToolBar(){
        //给toolBar设置item数组
        var items = [UIBarButtonItem]()
        //想数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        
        //遍历配置的数组
        for item in itemSettings{
            
            let imageName = item["imageName"]
            let btn = UIButton(imageName: nil, backgroundImageName: imageName!)
            
            
            //addtarget可以将字符转直接转换为Selector类型，但是如果传递的是参数就无法自动包装
            if let action = item["actionName"] {
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            
            let barButtonItem = UIBarButtonItem(customView: btn)
            //添加到数组中
            items.append(barButtonItem)
            
            //添加弹簧按钮
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target:nil, action: nil)
            items.append(space)
            
        }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
        
        //添加到父视图
        view.addSubview(toolBar)
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            //  make.height.equalTo(35)
        }
        
        
    }
    
}
